<template>
  <div class="home">
    <div class="top">
      <a-config-provider :autoInsertSpaceInButton="false">
        <a-button
          type="primary"
          size="large"
          :autoInsertSpaceInButton="false"
          style="border-radius:0px;width:96px;font-size: 17px;"
          @click="showModal"
        >新增</a-button>
      </a-config-provider>
    </div>
    <div class="center">
      <div v-for="(item,index) in data" :key="index">
        <div class="title flexBetween">
          <div>{{item.place}}</div>
          <div>
            <a-button
              :autoInsertSpaceInButton="false"
              style="border-radius:4px;width:80px;height:35px;font-size: 15px;color:#fff;background:#08C179"
              @click="onEdit(item)"
            >
              <a-icon type="edit" class="a-icon" />编辑
            </a-button>
          </div>
        </div>
        <div class="content flexStart">
          <div>设立时间：{{item.releaseDate}}</div>
          <div>负责人：{{item.manager}}</div>
          <div>最后更新时间：{{item.updateTime}}</div>
        </div>
        <div class="flexStart" v-if="item.fileList.length!=0" >
          <div class="img" v-for="(data,index) in item.fileList" :key="index">
            <img :src="data.fileUrl" width="327px" height="212px" alt />
          </div>
        </div>
      </div>

      <!--
      <div class="title flexBetween">
        <div>
          员工宿舍
        </div>

        <div>
          <a-button
            :autoInsertSpaceInButton="false"
            style="border-radius:4px;width:80px;height:35px;font-size: 15px;color:#fff;background:#08C179"
            @click="onEdit"
          > <a-icon type="edit" class="a-icon" />编辑</a-button>
        </div>
      </div>
      <div class="content flexStart">
        <div>设立时间：2021年3月11日</div>
        <div>负责人：张晓</div>
        <div>最后更新时间：2021年3月11日</div>
      </div>
      <div class="img flexStart">
        <div>
          <img src="@/assets/img/weiquan.png" width="327px" height="212px" alt />
        </div>
        <div>
          <img src="@/assets/img/weiquan.png" width="327px" height="212px" alt />
        </div>
      </div>-->
    </div>
    <!-- 对话框 -->
    <a-modal
      v-model="visible"
      :title="modalTitle"
      @ok="handleOk"
      :maskClosable="false"
      cancelText="取消"
      okText="确认"
    >
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        v-if="visible"
      >
        <a-form-model-item ref="place" label="地点" prop="place">
          <a-input
            v-model="form.place"
            @blur="
          () => {
            $refs.place.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item ref="releaseDate" label="设立时间" prop="releaseDate">
          <a-date-picker
            v-model="form.releaseDate"
            type="date"
            placeholder="请选择日期"
            style="width: 100%;"
          />
        </a-form-model-item>

        <a-form-model-item ref="manager" label="负责人" prop="manager">
          <a-input
            v-model="form.manager"
            @blur="
          () => {
            $refs.manager.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item label="备注">
          <a-input v-model="form.remark" type="textarea" />
        </a-form-model-item>

        <a-form-model-item label="维权信息告示牌" prop="formUpload">
          <div class="clearfix">
            <a-upload
              list-type="picture-card"
              :default-file-list="fileList"
              :remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <div v-if="fileList.length < 8">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import {
  rightProtectionBoardAdd,
  rightProtectionBoardQuery,
  rightProtectionBoardGet,
  rightProtectionBoardUpdate,
  rightProtectionBoardDelete
} from '@/api/rightProtectionBoard.js'
import { uploadOSS } from '@/utils/oss.js'
export default {
  data() {
    let formUpload = (rule, value, callback) => {
      // console.log(this.fileList.length);

      if (this.imgupload == false) {
        callback(new Error('请上传图片'))
      } else {
        this.$refs.ruleForm.validateField('formUpload')
        callback()
      }
    }
    return {
      modalTitle: '新增维权广告牌',
      visible: false,
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 12
      },
      form: {
        id: '',
        packageId: '',
        fileInfoList: [],
        manager: '',
        place: '',
        releaseDate: moment(new Date()),
        remark: ''
      },
      previewVisible: false,
      previewImage: '',
      fileList: [],
      imgupload: false,
      data: [],
      rules: {
        place: [
          {
            required: true,
            message: '请输入地点',
            trigger: 'change'
          }
        ],
        releaseDate: [
          {
            required: true,
            message: '请输入设立时间',
            trigger: 'change'
          }
        ],
        manager: [
          {
            required: true,
            message: '请输入负责人',
            trigger: 'change'
          }
        ],
        formUpload: [
          {
            required: true,
            validator: formUpload,
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted() {
    this.getTable()
  },
  methods: {
    moment,
    getTable() {
      let data1 = {}
      data1.likeName = ''
      data1.page = 0
      data1.size = 0
      let _this = this
      rightProtectionBoardQuery(data1).then((res) => {
        let tabdata = res.data.data
        _this.data = []
        tabdata.forEach((item, index) => {
          item.key = item.id
          item.releaseDate = moment(item.releaseDate).format('YYYY-MM-DD')
          item.updateTime = moment(item.updateTime).format('YYYY-MM-DD')
          item['description'] = {}
          item['description']['data'] = item.fileList
          item['description']['people'] = item.updateId
          item['description']['updateTime'] = item.updateTime
        })
        _this.data = tabdata
        this.total = res.data.total
        // console.log(tabdata);
      })
    },
    onEdit(item) {
      this.modalTitle = '编辑维权广告牌'
      this.form.packageId = ''
      this.form.fileInfoList = []
      this.fileList = []
      this.form.place = ''
      this.form.releaseDate = moment(new Date())
      this.form.manager = ''
      this.form.remark = ''
      this.form.place = item.place
      this.form.releaseDate = moment(new Date(item.releaseDate))
      this.form.remark = item.remark
      this.form.id = item.id
      this.form.manager = item.manager
      this.form.packageId = item.packageId
      item.fileList.forEach((itemData, index) => {
        let fileObj = {}
        fileObj['uid'] = index
        fileObj['status'] = 'done'
        fileObj['url'] = itemData.fileUrl
        fileObj['name'] = itemData.fileName
        this.form.fileInfoList.push(fileObj)
        this.fileList.push(fileObj)
      })
      if (this.fileList.length != 0) this.imgupload = true
      this.visible = true
    },
    showModal() {
      this.form.packageId = ''
      this.form.fileInfoList = []
      this.fileList = []
      this.form.place = ''
      this.form.releaseDate = moment(new Date())
      this.form.manager = ''
      this.form.remark = ''
      this.modalTitle = '新增维权广告牌'
      this.visible = true
    },
    handleOk(e) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = {}
          data['fileInfoList'] = []
          this.form.fileInfoList.forEach((item, index) => {
            let obj = { fileName: '', fileUrl: '' }
            obj.fileName = item.name
            obj.fileUrl = item.url
            data['fileInfoList'].push(obj)
          })
          data.place = this.form.place
          data.manager = this.form.manager
          data.releaseDate = this.form.releaseDate
          data.id = this.form.id
          data.packageId = this.form.packageId
          data.remark = this.form.remark
          if (this.modalTitle != '编辑维权广告牌') {
            rightProtectionBoardAdd(data).then((res) => {
              console.log(res)
              this.$message.success('新增成功')
              this.visible = false
              this.getTable()
            })
          } else {
            rightProtectionBoardUpdate(data)
              .then((res) => {
                console.log(res)
                this.$message.success('编辑成功')
                this.visible = false
                this.getTable()
              })
              .catch((err) => {})
          }
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      console.log(1111)

      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleRemove(file) {
      console.log(file.uid)
      this.form.fileInfoList.forEach((item, index) => {
        if (file.uid == item.uid) {
          this.form.fileInfoList.splice(index, 1)
        }
      })
      if (this.form.fileInfoList.length != 0) {
        this.imgupload = true
      } else {
        this.imgupload = false
      }
      // this.form.fileInfoList
    },

    beforeUpload(file) {
      // console.log(file)
      const reader = new FileReader()
      reader.readAsDataURL(file) // 读取图片文件
         if (this.modalTitle != '编辑维权广告牌') {
        this.form.packageId = file.uid
      }
      reader.onload = (data) => {
        //  console.log(file)
        this.uploadFile(data.target.result, file.name,  this.form.packageId)
      }
      this.imgupload = true

      this.$message.success(`${file.name} 上传成功`, 1)
      return false
    },
    uploadFile(base64Data, fileName, fileUid) {
      let blob = this.dataURLtoBlob(base64Data)
      let dir='lw/'+'RB'+fileUid+'/'
      uploadOSS(blob, fileName,dir).then((fileUrl) => {
        // console.log(fileUrl, fileName)
        let obj = { url: fileUrl, name: fileName, uid: fileUid }
        // console.log( obj.fileUid );
        this.form.fileInfoList.push(obj)
      })
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    }
  }
}
</script>

<style scope lang="less">
.home {
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #333333;
}

.top {
  margin-bottom: 10px;
  background: #fff;
  padding: 18px 30px;
}

.center {
  padding: 15px 30px;
  background: #fff;
}

.title {
  font-size: 20px;
  color: #333333;
  height: 50px;
  padding-top: 11px;
  line-height: 31px;
  border-bottom: 1px solid #e4e4e4;
  padding-bottom: 19px;
  margin-bottom: 25px;
}

.content {
  font-weight: 400;
  color: #999999;
  // line-height: 31px;
  font-size: 16px;
  margin-bottom: 30px;
}

.content div {
  margin-right: 60px;
}

.img {
  width: 327px;
  height: 212px;
  margin-bottom: 30px;
  margin-right: 84px;
}

.img div {
  margin-right: 44px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.a-icon {
  cursor: pointer;
}

.flexBetween {
  align-items: center;
}
</style>
